<template>
    <fieldset>
        <legend>失效函数</legend>
        <h1 id="content">
            {{content}}
        </h1>
        <button v-for="(btn,index) in buttons" :key="index" @click="handleClick(index+1)" :class="{active:index+1===flagmsg}">{{btn}}</button>
    </fieldset>
</template>


<script setup>
import {onMounted, ref, watchEffect} from "vue"

import CancelPromise from "./cancelPromise"
let buttons = ref(['第1页','第2页','第3页'])

let api1 = signal => new CancelPromise((resolve,reject) => {
    setTimeout(()=>{
        resolve('第一页数据')
    },1000)
},signal)

let api2 = signal => new CancelPromise((resolve,reject) => {
    setTimeout(()=>{
        resolve('第二页数据')
    },1500)
},signal)

let api3 = signal => new CancelPromise((resolve,reject) => {
    setTimeout(()=>{
        resolve('第三页数据')
    },2000)
},signal)



let api = {
    api1,
    api2,
    api3
}

let flagmsg = ref(1)

let handleClick = function(current){
    flagmsg.value = current
    // console.log(flagmsg.value)
    // fetchData(current)
}


let content = ref('')

/**
 * 
 * @param {Number} current 传递给后端的页码
 * @param {Object} signal 控制器(AbortConstroller)的signal对象
 */
let fetchData = (current=1,signal) =>{
    api['api'+current](signal)
        .then(res =>{
            content.value = res
        })
}


watchEffect(invalidate => {
    // 声明一个控制
    let abortConstroller = new AbortController();
    // 获取signal对象
    let signal = abortConstroller.signal;
    // 发起请求并且传入signal对象
    fetchData(flagmsg.value,signal)
    invalidate(()=>{
        // 页码切换之前，取消上一个Promise
        abortConstroller.abort()
    })
})

// onMounted(()=>{
//     fetchData(1)
// })

</script>


<style scoped>

    .active{
        background-color: pink;
    }


</style>